
var MakeCoupon = new Class({
    Implements: Options,
    options: {
        'tagid':''
    },
    panel: null,
    content: null,
    listData: null,
    result:null,
    resGroupPrice:0,
    resGroupQty:0,
    initialize: function(opts) {
        this.setOptions(opts);

        this.panel = document.id(this.options.tagid);
        if(!this.panel) return;
        this.panel.empty();

        this.createTable();
    },
    createTable: function() {
        this.content = new Element('div#content');
        this.listData = new Element('div');

        this.panel.adopt(
            new Element('div.tl[html=<div class="tr"><div>&nbsp;</div></div>]'),
            this.content.adopt(this.listData),
            new Element('div.bl[html=<div class="br"><div>&nbsp;</div></div>]')
        )

        this.divData = new Element('div');
        this.listData.adopt(
            new Element('b[text=AccwareSKU : ]'),
            new Element('input[size=13][maxlength=15][type=text]'),
            new Element('button[text=GET]',{
                'events': {
                    'click': this.getItem.bind(this),
                    'focus': function() {this.blur();}
                }
            }),
            this.divData
        );
    },
    getItem: function(ev) {
        ev.stop();

        var sku = this.listData.getElement('input');
        if(sku.get('value') == '') {
            alert('AccwareSKU cannot be empty.'); return;
        }

        this.getItem = new Request({
            url: '/Admin/webstat/getFromMySQL',
            method: 'get',
            onRequest: function() {
                new ShowBox().say('Get Item...');
                new Loader().show();
            },
            onComplete: function(resp) {
                var data = [];
                try {
                    data = eval('(' + resp + ')');
                }
                catch(err) { alert('Error...\n' + err); return; }
                new Loader().hide();

                this.showItem(data);
            }.bind(this)
        }).send('table=cupon&ex=getItem&sku=' + sku.get('value') + '&nc=' + Date.now());
    },
    showItem: function(item) {

        this.divData.empty();

        this.itemid = item.itm.id;
        this.divData.adopt(
            new Element('hr'),
            new Element('div[html=<h3>' + item.itm.iname + '</h3>][style=margin:10px;]'),
            new Element('table',{'width':'50%'}).adopt(
                new Element('tbody').adopt(
                    new Element('tr',{'valign':'top'}).adopt(
                        new Element('td').adopt(this.itemBody(item.itm)),
                        new Element('td').adopt(this.newCoupon(item.itm))
                    )
                )
            ),
            new Element('hr[style=margin:10px 0;]'),
            this.itemCoupons(item.cpns)
        );
    },
    newCoupon: function(item) {

        this.coupon = 'R' + ('' + Number.random(0, 999999) + 1000000).substring(1,7);

        var tbody = new Element('tbody');
        new Element('tr').adopt(
            new Element('td[html=<hr/><b>Coupon:</b> <b class="green">CV' + this.coupon + '</b>]')
        ).inject(tbody);

        new Element('tr').adopt(
            new Element('td[html=<hr/><b>Select Procent:</b>]')
        ).inject(tbody);

        var price;
        [5,7.5,10,12.5,15,20,25,30].each(function(procent) {
            price = item.sell - (item.sell * (procent / 100));
            new Element('tr').adopt(
                new Element('td').adopt(
                    new Element('input[type=radio][name=promPrice][value=' + price + '][title=' + procent + ']'),
                    new Element('span[html=&nbsp;&nbsp;(' + procent + '%) <b>$' + numberFormat(price) + '</b> <em>$' + numberFormat(item.sell - price) + ' off</em>]')
                )
            ).inject(tbody);
        });

        new Element('tr').adopt(
            new Element('td[html=<hr/><b>or <b class="red">Set</b> discount price:</b>]')
        ).inject(tbody);
        new Element('tr').adopt(
            new Element('td').adopt(
                new Element('input[type=text][name=price][style=width:90px;]'),
                new Element('em#showProc[style=padding-left:6px;color:green;]')
            )
        ).inject(tbody);

        new Element('tr').adopt(
            new Element('td[html=<hr/><b>Select Expare date:</b>]')
        ).inject(tbody);

        // set calendar
        this.begDate = new Element('input[type=text][name=pricest][style=width:90px;]');
	new DatePicker(this.begDate, {
            startDate: new Date().increment('day', 30)
        });
        new Element('tr').adopt(
            new Element('td').adopt(this.begDate)
        ).inject(tbody);


        tbody.adopt(
            new Element('tr').adopt(
                new Element('td[html=<hr/><b>Select time use:</b>]')
            ),
            new Element('tr').adopt(
                new Element('td').adopt(
                    new Element('input[type=radio][name=time][value=one][checked=checked]'),
                    new Element('span[text= One Time]')
                )
            ),
            new Element('tr').adopt(
                new Element('td').adopt(
                    new Element('input[type=radio][name=time][value=many]'),
                    new Element('span[text= Multi Use]')
                )
            ),
            new Element('tr').adopt(
                new Element('td[html=<hr/><b>and click to create:</b>]')
            ),
            new Element('tr').adopt(
                new Element('td').adopt(
                    new Element('button[text=Create New Coupon]',{
                        'events': {
                            'click': this.saveCoupon.bind(this),
                            'focus': function() {this.blur();}
                        }
                    })
                )
            )
        );

        this.table =  new Element('table#percup').adopt(tbody);
        return this.table;
    },
    saveCoupon: function(ev) {
        ev.stop();

        var time = this.table.getElements('input[name=time]').filter('input:checked')[0].get('value');
        var disPrice = this.table.getElement('input[name=price]').get('value');
        var promPrice = this.table.getElements('input[name=promPrice]').filter('input:checked')[0];

        if(!promPrice && !disPrice) {
            alert('Select Procent or Set discount price.');
            return;
        }
        var price = 0;
        var proc = 0;
        var disProc = 100 - (((this.sellPrice - disPrice) * 100) / this.sellPrice);

        if(time == 'one') {
            price = promPrice ? promPrice.get('value') : disPrice;
        }
        else if(time == 'many') {
            proc = promPrice ? promPrice.get('title') : disProc;
        }
        else {
            alert('Select Procent or Set discount price or some error.');
            return;
        }

        if(disPrice) {
            document.id('showProc').set('text', numberFormat(disProc) + '%')
        }

        ev.target.set('disabled', true);

        this.saveItem = new Request({
            url: '/Admin/webstat/getFromMySQL',
            method: 'post',
            onRequest: function() {
                new ShowBox().say('Create Coupon...');
                new Loader().show();
            },
            onComplete: function() {
                new Loader().hide();
            }
        }).send('table=cupon&ex=saveCoupon&iid=' + this.itemid + '&code=' + this.coupon + '&price=' + price + '&proc=' + proc + '&date=' + this.begDate.value + '&nc=' + Date.now());

    },
    itemBody: function(item) {
        // Item
        this.sellPrice = item.sell;
        var table = new Element('table',{'id':'itmcup'}).adopt(
            new Element('tbody').adopt(
                new Element('tr').adopt(new Element('th[text=AccwareSKU]'), new Element('td[text=' + item.sku + ']')),
                new Element('tr').adopt(new Element('th[text=Category Name]'), new Element('td[text=' + item.cname + ']')),
                new Element('tr').adopt(new Element('th[text=Vendor Name]'), new Element('td[text' + item.vname + ']')),
                new Element('tr').adopt(new Element('th[text=Cost Price]'), new Element('td[html=<b class="red">$' + numberFormat(item.cost) + '</b>]')),
                new Element('tr').adopt(new Element('th[text=Sell Price]'), new Element('td[html=<b class="green">$' + numberFormat(item.sell) + '</b>]')),
                new Element('tr').adopt(new Element('th[text=Profit]'), new Element('td[text' + (numberFormat((item.sell - item.cost) / item.sell * 100)) + '%]')),
                new Element('tr').adopt(new Element('th[text=Hot Price]'), new Element('td[text=$' + numberFormat(item.hot) + ']')),
                new Element('tr').adopt(new Element('th[text=Drop Price]'), new Element('td[text=$' + numberFormat(item.drop) + ']')),
                new Element('tr').adopt(new Element('th[text=Stock]'), new Element('td=text=' + item.stock + ']')),
                new Element('tr').adopt(new Element('th[text=Quantity]'), new Element('td[text=' + item.qty + ']')),
                new Element('tr').adopt(new Element('th[text=Mfr Name]'), new Element('td[text=' + item.mfrName + ']')),
                new Element('tr').adopt(new Element('th[text=Mfr Number]'), new Element('td[text=' + item.mfrNumber + ']')),
                new Element('tr').adopt(new Element('th[text=Oldest]'), new Element('td[text=' + item.older + ']'))
            )
        );
        return table;
    },
    itemCoupons: function(coupons) {
        if(!coupons.length) {
            return new Element('div[html=<b>Don\'t have old coupons.</b>][style=text-align:center;]')
        }

        var tbody = new Element('tbody').adopt(
            new Element('tr', { html:
                '<th>Coupon</th><th>%</th><th>Discount price</th><th>Used</th><th>Exp. Date</th><th>Oldest</th><th>Set New Date</th>'
            })
        );

        coupons.each(function(coupon, idx) {
            tbody.adopt(
                new Element('tr[style=background-color:#' + (idx % 2 ? 'fcffcd' : 'ffffff' ) + ';]').adopt(
                    new Element('td[text=CV' + coupon.code + '][style=text-align:left;]'),
                    new Element('td[text=' +  (coupon.proc ? numberFormat(coupon.proc) : ' ') + ']'),
                    new Element('td[text=' + (coupon.price ? '$' + numberFormat(coupon.price) : '') + ']'),
                    new Element('td[text=' + (coupon.cnt ? coupon.cnt : '') + ']'),
                    new Element('td[text=' + Date.parse(coupon.endDate).format('%b %d %Y') + ']'),
                    new Element('td.' + (coupon.oldest > 0 ? 'green' : 'red') + '[text=' + coupon.oldest + ' days]'),
                    new Element('td').adopt(new Element('input[type=radio][name=upd][value=' + coupon.id + ']'))
                )
            );
        });

        var dateTag = new Element('input[type=text][name=date][style=width:80px;]');
	new DatePicker(dateTag, {
            format: '%Y-%m-%d',
            startDate: new Date().increment('day', 30)
        });
        tbody.adopt(
            new Element('tr').adopt(
                new Element('th[colspan=7][style=text-align:right;]').adopt(
                    dateTag,
                    new Element('button[text=Update Old Coupon]',{
                        'events': {
                            'click': this.updateCoupon.bind(this),
                            'focus': function() {this.blur();}
                        }
                    })
                )
            )
        );

        this.ctable = new Element('table#cpntbl').adopt(tbody);
        return this.ctable;
    },
    updateCoupon: function(ev) {
        ev.stop();
        ev.target.set('disabled', true);
        var inps = this.ctable.getElements('input');

        var id = 0;
        var date = '';
        inps.each(function(inp) {
            if(inp.get('checked')) {
                id = inp.get('value');
            }
            if(inp.get('type') == 'text') {
                date = inp.get('value');
            }
        });
        if(!id) return;

        this.updateItem = new Request({
            url: '/Admin/webstat/getFromMySQL',
            method: 'post',
            onRequest: function() {
                new ShowBox().say('Update Coupon...');
                new Loader().show();
            },
            onComplete: function() {
                new Loader().hide();
            }
        }).send('table=cupon&ex=updateCoupon&id=' + id + '&date=' + date + '&nc=' + Date.now());
    }
});
